package com.concurrency.example.cancle;

import com.concurrency.annoations.ThreadSafe;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@ThreadSafe
public class PrimeGenerator implements Runnable {
    private final List<BigInteger> prims = new ArrayList<>();
    private volatile boolean cancelled = false;

    @Override
    public void run() {
        BigInteger bigInteger = BigInteger.ONE;
        while (!cancelled) {
            //获取下一个素数
            bigInteger = bigInteger.nextProbablePrime();
            synchronized (this) {
                prims.add(bigInteger);
            }
        }
    }

    public void cancel() {
        cancelled = true;
    }

    public synchronized List<BigInteger> getPrims() {
        return new ArrayList<>(prims);
    }

    public static void main(String[] args) {
        PrimeGenerator primeGenerator = new PrimeGenerator();
        new Thread(primeGenerator).start();
        try{
            TimeUnit.SECONDS.sleep(1);
            primeGenerator.cancel();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {

        }
        System.out.println(primeGenerator.getPrims());
    }
}
